package com.example.kotlin

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import kotlin.reflect.KProperty

/**
 * 配置入手
 * 1.开启R8
 * 2.配置基本配置文件（covering your bases）
 * */


/**
 * 代码入手
 * Compose 包含三个主要阶段 组合 布局 绘制
 * */

//不要向后运行,在组合完成前应该保持不变，这里出现的问题就是对已经在组合中读取的值进行了写入，对已读取的数据进行写入
// balance += transaction -》 Text-》  balance += transaction ——》Text-》  balance += transaction -》Text
@Composable
private fun RunningBackwards() {
    var balance by remember {
        mutableStateOf(0)
    }
    balance = 0
    for (transaction in 1..10) {
        Row() {
            balance += transaction
            Text(text = "transaction:$transaction,balance:$balance ")
        }
    }
}

//延迟读取
@Composable
private fun UseDrawBehind() {
    val color by animateColorBetween(Color.White, Color.Black)//颜色变化动画
    //错误
    Box(modifier = Modifier.background(color = color))
    //正确
    Box(modifier = Modifier.drawBehind {
        //这样修改，绘制阶段就变成唯一需要重新执行的阶段
        //在函数中读取而不是在组合函数中读取
        drawRect(color)
    })
}
//for test
private operator fun Color.getValue(nothing: Nothing?, property: KProperty<*>): Color {
    return property.getter as Color
}

fun animateColorBetween(white: Color, black: Color): Color {
    return Color.Black
}
//衍生变化
@Composable
private fun DerivingChange() {
    val listState = rememberLazyListState()
    //错误
//    val showButton = listState.firstVisibleItemIndex > 0
    //正确
    val showButton by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }
    LazyColumn(state = listState) {

    }
    AnimatedVisibility(visible = showButton) {

    }
}



@Preview(showBackground = true)
@Composable
private fun Preview() {
    RunningBackwards()

}